layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage,
        layer = layui.layer;

    // 发起ajax请求
    async function getList() {
        let res = await pAjax({
            url: './php/list.php',
            dataType: 'json'
        })
        console.log(res);
        let {
            data
        } = res; // 解构赋值

        //调用分页
        laypage.render({
            elem: 'demo5',
            count: data.length,
            limit: 16,
            limits: [4, 8, 16],
            layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
            jump: function (obj) {
                //模拟渲染
                document.getElementById('main').innerHTML = function () {
                    var arr = [],
                        thisData = data.concat().splice(obj.curr * obj.limit - obj
                            .limit, obj.limit);

                    layui.each(thisData, function (index, item) {
                        arr.push(`<div class="commi">
                        <img src="${item.imgpath.split('==========')[0]}" alt="...">
                        <div>${item.name}</div>
                        <div>
                          <span>${item.price}</span>
                          <span class="addbuy" data-id=${item.id}>加入购物车</span>
                        </div>
                      </div>`);
                    });
                    return arr.join('');
                }();
                let itemdiv = document.querySelectorAll('.commi');
                console.log(itemdiv);
                for (let i = 0; i < itemdiv.length; i++) {
                    itemdiv[i].onclick = function (e) {
                        // 给列表页的.list的div绑定点击事件，帮ul中的li的a标签
                        console.log(e.target.dataset.id);
                        if (e.target.className === 'addbuy') {
                            // 将商品的id存储在sessionStorage
                            sessionStorage.setItem('goodsId', e.target.dataset.id);
                            // 跳转至详情页面
                            location.assign("./shopindex.html")
                        }
                    }
                }
            }
        });

    }
    getList()
});